Desk = {}
Component = require('component')
Ser = require('serialization')
event = require('event')
thread=require('thread')
Desk.getUsedRefinedStorageForItem = function()
    local sum = 0
    local grid_0 = Component.block_refinedstorage_grid_0
    local res = grid_0.getStorages()
    local devices = res['devices']
    for i, v in ipairs(devices) do
        if v['type'] == 'item' then
            sum = sum + v['usage']
        end
    end
    return sum
end
Desk.getTotalRefinedStorageForItem = function()
    local sum = 0
    local grid_0 = Component.block_refinedstorage_grid_0
    local res = grid_0.getStorages()
    local devices = res['devices']
    for i, v in ipairs(devices) do
        if v['type'] == 'item' then
            sum = sum + v['capacity']
        end
    end
    return sum
end
Desk.recShowStorageInfo = function(resX, resY)
    if resX ~= nil and resY ~= nil then
        Component.gpu.setResolution(resX, resY)
    end

    while (true) do
        os.execute('cls')
        local used = Desk.getUsedRefinedStorageForItem()
        local total = Desk.getTotalRefinedStorageForItem()
        print('used:' ..
        tostring(used) .. '\ntotal:' .. tostring(total) .. '\nperc:' .. string.format('%.2f', 100 * used / total) .. '%')
        os.sleep(1)
    end
end
Desk.recShowStorageUsedPercentage = function()
    Component.gpu.setResolution(7, 2)

    while (true) do
        os.execute('cls')
        local used = Desk.getUsedRefinedStorageForItem()
        local total = Desk.getTotalRefinedStorageForItem()
        print(string.format('%.2f', 100 * used / total) .. '%')
        os.sleep(1)
    end
end
--[[
开启一个服务，内容是获取itemCount,采用p2p连接卡
输入格式：
tunnel.send(stack经过序列化后得到的String)
返回格式：
{bool,msg,data}经过序列化后得到的String
 ]]
Desk.openServerForGettingItemCount = function()
    local tunnel = Component.tunnel
    local grid_0 = Component.block_refinedstorage_grid_0
    
    while true do
        local msgType, addTo, addFrom, portTo, portFrom, msg = event.pull('modem_message')
        local stack = Ser.unserialize(msg)
        local OK, res = pcall(grid_0.getItem, stack)
        if OK then
            local count
            if res == nil then
                count = 0
            else
                count = res['size']
            end
            tunnel.send(Ser.serialize({ res=OK, msg='OK', data=count }))
        else
            tunnel.send(Ser.serialize({ res=OK, msg='error', data=res }))
            
        end
    end
end
Desk.backgroundRun=function(func,...)
    local threadHandle=thread.create(func,...)
    threadHandle:detach();
    return threadHandle;
end

return Desk
